package com.ruoyi.api.controller;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.DzHuiyuan;
import com.ruoyi.system.service.IDzHuiyuanService;
import com.ruoyi.system.service.IDzShitiService;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.WxDecPhone;
import com.ruoyi.common.enums.BusinessType;

/**
 * 获取微信手机号Controller
 *
 * @author
 * @date 2022-03-23
 */
@RestController
@RequestMapping("/api/phone")
public class WxController extends BaseController {


    @Autowired
    private IDzHuiyuanService zzHuiyuanService;
    // 小程序appid
    private String APP_ID="wxe1618efed27fb8d3";
    // 小程序的app secret
    private String APPSECRET="02d0fe578f5bab5ab28f6a96f905cf35";

    @PostMapping("/bind")
    public AjaxResult deciphering(@RequestBody WxDecPhone wxDecPhone) {
        String code = wxDecPhone.getCode();//code 为getPhoneNumber(e)后的e.detail.code
        String phone = "";
        String access_token = getAccess_token();
        System.out.println("code:" + code);
        System.out.println("access_token:" + access_token);

        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + access_token;
        JSONObject body = new JSONObject();
        body.put("code", code);
        try {
            String ret = httpPostRaw(url, body.toString(), null, null);
            System.out.println("ret:" + ret);
            if(ret != null && !"".equals(ret)) {
                JSONObject json = JSONObject.parseObject(ret);
                JSONObject phone_info = json.getJSONObject("phone_info");
                phone = phone_info.getString("phoneNumber");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        DzHuiyuan huiyuan =  zzHuiyuanService.selectDzHuiyuanByDn(phone);
        if(huiyuan!=null){
            AjaxResult ajax = AjaxResult.success(huiyuan);
            return ajax;
        }else{
            DzHuiyuan huiyuan1 = new DzHuiyuan();
            huiyuan1.setLoginname(phone);
            huiyuan1.setDn(phone);
            huiyuan1.setUserType(0l);
            huiyuan1.setUsername(phone);
            huiyuan1.setPassword(SecurityUtils.encryptPassword(phone));
            huiyuan1.setUserPic("/profile/upload/header.jpg");
            zzHuiyuanService.insertDzHuiyuan(huiyuan1);

            AjaxResult ajax = AjaxResult.success(huiyuan1);
            return ajax;
        }




    }

    /**
     * 微信接口请求令牌：生产环境下 要用redis缓存起来
     * @return
     */
    public String getAccess_token() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + APP_ID + "&secret=" + APPSECRET;
        String accessToken = null;
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            JSONObject demoJson = JSONObject.parseObject(message);
            accessToken = demoJson.getString("access_token");
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }

    /**
     * 参数以raw的方式做post请求
     *
     * @param url
     * @param stringJson
     * @param headers
     * @param encode
     * @return
     */
    public static String httpPostRaw(String url, String stringJson, Map<String, String> headers, String encode) {
        String str = "";
        if (encode == null) {
            encode = "utf-8";
        }
        // HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        HttpPost httpost = new HttpPost(url);

        // 设置header
        httpost.setHeader("Content-type", "application/json");
        if (headers != null && headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpost.setHeader(entry.getKey(), entry.getValue());
            }
        }
        // 组织请求参数
        StringEntity stringEntity = new StringEntity(stringJson, encode);
        httpost.setEntity(stringEntity);
        String content = null;
        CloseableHttpResponse httpResponse = null;
        try {
            // 响应信息
            httpResponse = closeableHttpClient.execute(httpost);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, encode);
            System.out.println(content);
            str = content;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try { // 关闭连接、释放资源
            closeableHttpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str;
    }

}